import { PlusOutlined } from '@ant-design/icons';
import {
  ActionType,
  PageContainer,
  ProColumns,
  ProTable,
} from '@ant-design/pro-components';
import { Button, message, Popconfirm } from 'antd';
import React, { useRef, useState } from 'react';
import { api } from '@/services/api';
import type { Group } from '@/services/generated/models';
import RoleForm from './components/RoleForm';
import { useAccess, Access } from '@umijs/max';

const RolesPage: React.FC = () => {
  const [createModalVisible, setCreateModalVisible] = useState(false);
  const [editModalVisible, setEditModalVisible] = useState(false);
  const [currentRole, setCurrentRole] = useState<Group>();
  const actionRef = useRef<ActionType>();
  const access = useAccess();

  // 表格列定义
  const columns: ProColumns<Group>[] = [
    {
      title: 'ID',
      dataIndex: 'id',
      search: false,
    },
    {
      title: '角色名称',
      dataIndex: 'name',
      copyable: true,
    },
    {
      title: '操作',
      valueType: 'option',
      render: (_, record) => {
        // 如果当前用户是超级管理员，则显示所有操作
        const canOperate = access.isSuperuser;
        return [
          <Access key="edit" accessible={access.canChangeGroup || canOperate}>
            <a
              onClick={() => {
                console.log('edit', record);
                setCurrentRole(record);
                setEditModalVisible(true);
              }}
            >
              编辑
            </a>
          </Access>,
          <Access key="delete" accessible={access.canDeleteGroup || canOperate}>
            <Popconfirm
              title="确定要删除该角色吗？"
              onConfirm={async () => {
                try {
                  await api.accounts.accountsGroupsDestroy({ id: record.id });
                  message.success('删除成功');
                  actionRef.current?.reload();
                } catch (error) {
                  message.error('删除失败');
                }
              }}
            >
              <a>删除</a>
            </Popconfirm>
          </Access>,
        ];
      },
    },
  ];

  return (
    <PageContainer>
      <ProTable<Group>
        headerTitle="角色列表"
        actionRef={actionRef}
        rowKey="id"
        search={false}
        toolBarRender={() => [
          <Access key="add" accessible={access.canAddGroup}>
            <Button
              type="primary"
              onClick={() => setCreateModalVisible(true)}
            >
              <PlusOutlined /> 新建
            </Button>
          </Access>,
        ]}
        request={async () => {
          try {
            const data = await api.accounts.accountsGroupsList({});
            return {
              data,
              success: true,
            };
          } catch (error) {
            console.error('获取角色列表失败:', error);
            message.error('获取角色列表失败');
            return {
              data: [],
              success: false,
            };
          }
        }}
        columns={columns}
      />

      <Access accessible={access.canAddGroup}>
        <RoleForm
          visible={createModalVisible}
          onVisibleChange={setCreateModalVisible}
          onSuccess={() => {
            setCreateModalVisible(false);
            actionRef.current?.reload();
          }}
        />
      </Access>

      <Access accessible={access.canChangeGroup}>
        <RoleForm
          visible={editModalVisible}
          onVisibleChange={setEditModalVisible}
          onSuccess={() => {
            setEditModalVisible(false);
            actionRef.current?.reload();
          }}
          role={currentRole}
        />
      </Access>
    </PageContainer>
  );
};

export default RolesPage;
